<template>
  <div id="app">
    <!-- 主布局：侧边栏 + 主内容区 -->
    <div class="main-layout">
      <!-- 侧边栏导航（固定） -->
      <div class="sidebar-nav">
        <div class="sidebar-header">
          <h1>🚁 P600 控制中心</h1>
        </div>
        <el-menu
          :default-active="$route.path"
          class="admin-menu"
          router
          background-color="#1a2b3c"
          text-color="#bfcbd9"
          active-text-color="#409EFF"
          active-background-color="#263445"
        >
          <el-menu-item index="/admin/home">
            <i class="el-icon-s-home"></i>
            <span>管理首页</span>
          </el-menu-item>
          <el-menu-item index="/admin/home/news-manage">
            <i class="el-icon-news"></i>
            <span>新闻管理</span>
          </el-menu-item>
          <el-menu-item index="/admin/home/product-manage">
            <i class="el-icon-goods"></i>
            <span>产品管理</span>
          </el-menu-item>
          <el-menu-item index="/admin/home/user-manage">
            <i class="el-icon-user"></i>
            <span>用户管理</span>
          </el-menu-item>
          <el-menu-item index="/admin/home/setting">
            <i class="el-icon-setting"></i>
            <span>系统设置</span>
          </el-menu-item>
        </el-menu>
      </div>

      <!-- 主内容区 -->
      <div class="main-content">
        <!-- 管理页面区域 -->
        <div v-if="isManagementPage" class="management-area">
          <router-view></router-view>
        </div>

        <!-- 飞行控制区域（仅在管理首页显示） -->
        <div v-else class="control-area">
          <!-- 顶部小状态栏（恒显） -->
          <div class="status-bar">
            <div class="status-item">
              <label>ROS连接:</label>
              <span :class="{ 'connected': isConnected }">{{ isConnected ? '✅ 已连接' : '❌ 未连接' }}</span>
            </div>
            <div class="status-item">
              <label>无人机状态:</label>
              <span class="control-state">{{ uavStateText }}</span>
            </div>
            <div class="status-item">
              <label>飞行模式:</label>
              <span class="mode-value">{{ flightMode }}</span>
            </div>
            <div class="status-item">
              <label>电池电量:</label>
              <span class="battery" :class="getBatteryClass(batteryPercentage)">{{ Math.round(batteryPercentage) }}%</span>
            </div>
          </div>

          <!-- 功能按钮组（恒显） -->
          <div class="function-buttons">
            <button 
              @click="switchComponent('flightControl')"
              :class="['btn', activeComponent === 'flightControl' ? 'btn-active' : '']"
            >
              🛫 飞行控制中心
            </button>
            <button 
              @click="switchComponent('movementControl')"
              :class="['btn', activeComponent === 'movementControl' ? 'btn-active' : '']"
            >
              🎮 方向与移动控制
            </button>
            <button 
              @click="switchComponent('parameterSettings')"
              :class="['btn', activeComponent === 'parameterSettings' ? 'btn-active' : '']"
            >
              ⚙️ 参数设置与偏移控制
            </button>
            <button 
              @click="switchComponent('customDataSegment')"
              :class="['btn', activeComponent === 'customDataSegment' ? 'btn-active' : '']"
            >
              📊 自定义数据段管理
            </button>
            <button 
              @click="switchComponent('trajectoryPlanning')"
              :class="['btn', activeComponent === 'trajectoryPlanning' ? 'btn-active' : '']"
            >
              ✈️ 轨迹规划与栅格地图
            </button>
            <button 
              @click="switchComponent('egoPlanner')"
              :class="['btn', activeComponent === 'egoPlanner' ? 'btn-active' : '']"
            >
              🧭 自主规划器
            </button>
            <button 
              @click="switchComponent('spirecvControl')"
              :class="['btn', activeComponent === 'spirecvControl' ? 'btn-active' : '']"
            >
              👁️ 视觉系统控制
            </button>
          </div>

          <!-- 动态内容区（按需显示） -->
          <div class="content-area">
            <FlightControl
              v-if="activeComponent === 'flightControl'"
              :is-connected="isConnected"
              :armed="armed"
              :uav-connected="uavConnected"
              :control-state="controlState"
              :position="position"
              :attitude="attitude"
              @send-command="sendUAVCommand"
              @send-setup="sendSetup"
              @send-param-settings="sendParamSettings"
              @send-offset-pose="sendOffsetPose"
              @send-stop-control="sendStopControl"
            />

            <MovementControl
              v-if="activeComponent === 'movementControl'"
              :is-connected="isConnected"
              :armed="armed"
              :control-mode="controlMode"
              :step-size="stepSize"
              :yaw-ref="yawRef"
              :position="position"
              :attitude="attitude"
              @change-control-mode="controlMode = $event"
              @change-step-size="stepSize = $event"
              @change-yaw-ref="yawRef = $event"
              @move-forward="moveForward"
              @move-backward="moveBackward"
              @move-left="moveLeft"
              @move-right="moveRight"
              @move-up="moveUp"
              @move-down="moveDown"
              @hover="sendHover"
            />

            <ParameterSettings
              v-if="activeComponent === 'parameterSettings'"
              :is-connected="isConnected"
              @set-params="sendParamSettings"
            />

            <CustomDataSegment
              v-if="activeComponent === 'customDataSegment'"
              :is-connected="isConnected"
              :custom-data="customData"
              @add-custom-data="addCustomData"
              @remove-custom-data="removeCustomData"
              @send-custom-data="sendCustomDataSegment"
            />

            <TrajectoryPlanning
              v-if="activeComponent === 'trajectoryPlanning'"
              :is-connected="isConnected"
              :trajectory="trajectory"
              :current-position="position"
              @publish-trajectory="publishTrajectory"
              @execute-trajectory="executeTrajectory"
              @stop-trajectory="stopTrajectory"
              @update:trajectory="updateTrajectory"
              @log-message="addLog"
            />

            <EgoPlanner
              v-if="activeComponent === 'egoPlanner'"
              :is-connected="isConnected"
              @apply-gridmap-params="sendGridMapParams"
              @apply-planning-params="sendPlanningParams"
              @start-planning="startPlanning"
              @stop-planning="stopPlanning"
              @replan="replan"
              @clear-obstacles="clearObstacles"
              @set-planning-mode="setPlanningMode"
              @apply-visualization="applyVisualization"
            />

            <SpirecvControl
              v-if="activeComponent === 'spirecvControl'"
              :is-connected="isConnected"
              @send-vision-control="sendVisionControl"
              @send-vision-target="sendVisionTarget"
              @send-gimbal-control="sendGimbalControl"
              @send-attitude-correction="sendAttitudeCorrection"
              @start-tracking="startTracking"
              @stop-tracking="stopTracking"
              @reset-tracking="resetTracking"
              @apply-vision-params="applyVisionParams"
            />
          </div>

          <!-- ROS连接控制（恒显） -->
          <div class="control-section">
            <h3>🔗 ROS连接控制</h3>
            <div class="connection-controls">
              <input v-model="rosBridgeUrl" placeholder="ws://localhost:9090" class="url-input">
              <button @click="connectROS" class="btn btn-connect">{{ isConnected ? '重新连接' : '连接' }}</button>
              <button @click="disconnectROS" class="btn btn-disconnect" :disabled="!isConnected">断开</button>
            </div>
          </div>

          <!-- 操作日志（恒显） -->
          <div class="log-section">
            <div class="log-header">
              <h3>📝 操作日志</h3>
              <div class="log-controls">
                <button @click="clearLogs" class="btn btn-clear">清空日志</button>
                <span class="log-count">共 {{ logs.length }} 条</span>
              </div>
            </div>
            <div class="log-content">
              <div v-for="(log, index) in logs" :key="index" class="log-entry">{{ log }}</div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import ROSLIB from 'roslib';
import FlightControl from './FlightControl.vue';
import MovementControl from './MovementControl.vue';
import ParameterSettings from './ParameterSettings.vue';
import CustomDataSegment from './CustomDataSegment.vue';
import TrajectoryPlanning from './TrajectoryPlanning.vue';
import EgoPlanner from './EgoPlanner.vue';
import SpirecvControl from './SpirecvControl.vue';

export default {
  name: 'AdminHome',
  components: {
    FlightControl,
    MovementControl,
    ParameterSettings,
    CustomDataSegment,
    TrajectoryPlanning,
    EgoPlanner,
    SpirecvControl
  },
  data() {
    return {
      activeComponent: 'flightControl',
      ros: null,
      commandPublisher: null,
      setupPublisher: null,
      paramSettingsPublisher: null,
      customDataPublisher: null,
      offsetPosePublisher: null,
      stopControlPublisher: null,
      trajectoryPublisher: null,
      isConnected: false,
      rosBridgeUrl: 'ws://192.168.144.60:9090',
      
      controlMode: 'ENU',
      stepSize: 1.0,
      yawRef: 0,
      commandId: 1,
      
      flightMode: '未知',
      position: { x: 0, y: 0, z: 0 },
      attitude: { roll: 0, pitch: 0, yaw: 0 },
      batteryPercentage: 0,
      batteryVoltage: 0,
      batteryText: '未知',
      uavConnected: false,
      armed: false,
      modeText: '未知',
      gpsStatus: 0,
      locationSource: 0,
      odomValid: false,
      gpsNum: 0,
      
      uav_id: 1,
      range: 0,
      rel_alt: 0,
      velocity: [0, 0, 0],
      attitude_q: { x: 0, y: 0, z: 0, w: 1 },
      attitude_rate: [0, 0, 0],
      latitude: 0,
      longitude: 0,
      altitude: 0,
      
      customData: [],
      trajectory: { 
        header: { 
          seq: 0,
          stamp: { secs: 0, nsecs: 0 },
          frame_id: 'world'
        }, 
        poses: [] 
      },
      logs: [],
      
      controlState: 0
    };
  },
  computed: {
    uavStateText() {
      if (!this.uavConnected) return '未连接';
      if (!this.armed) return '已锁定';
      return '已解锁';
    },
    isManagementPage() {
      return this.$route.path !== '/admin/home';
    }
  },
  mounted() {
    this.connectROS();
  },
  methods: {
    switchComponent(componentName) {
      this.activeComponent = componentName;
    },

    connectROS() {
      try {
        if (this.ros) {
          this.ros.close();
        }

        this.addLog(`正在连接到: ${this.rosBridgeUrl}`);
        
        this.ros = new ROSLIB.Ros({
          url: this.rosBridgeUrl
        });

        this.ros.on('connection', () => {
          this.isConnected = true;
          this.addLog('✅ 成功连接到ROS Bridge');
          this.setupTopics();
        });

        this.ros.on('error', (error) => {
          this.isConnected = false;
          this.addLog('❌ ROS连接错误: ' + error);
        });

        this.ros.on('close', () => {
          this.isConnected = false;
          this.addLog('🔌 ROS连接已关闭');
        });

      } catch (error) {
        this.addLog('❌ 连接失败: ' + error.message);
      }
    },
    
    disconnectROS() {
      if (this.ros) {
        this.ros.close();
      }
      this.isConnected = false;
      this.addLog('手动断开ROS连接');
    },

    setupTopics() {
      this.commandPublisher = new ROSLIB.Topic({
        ros: this.ros,
        name: '/uav1/prometheus/command',
        messageType: 'prometheus_msgs/UAVCommand'
      });

      this.setupPublisher = new ROSLIB.Topic({
        ros: this.ros,
        name: '/uav1/prometheus/setup',
        messageType: 'prometheus_msgs/UAVSetup'
      });

      this.paramSettingsPublisher = new ROSLIB.Topic({
        ros: this.ros,
        name: '/uav1/prometheus/param_settings',
        messageType: 'prometheus_msgs/ParamSettings'
      });

      this.customDataPublisher = new ROSLIB.Topic({
        ros: this.ros,
        name: '/uav1/prometheus/set_customdatasegment',
        messageType: 'prometheus_msgs/CustomDataSegment'
      });

      this.offsetPosePublisher = new ROSLIB.Topic({
        ros: this.ros,
        name: '/uav1/prometheus/set_local_offset_pose',
        messageType: 'prometheus_msgs/GPSData'
      });

      this.stopControlPublisher = new ROSLIB.Topic({
        ros: this.ros,
        name: '/uav1/prometheus/stop_control_state',
        messageType: 'std_msgs/Bool'
      });

      this.trajectoryPublisher = new ROSLIB.Topic({
        ros: this.ros,
        name: '/uav1/prometheus/trajectory',
        messageType: 'nav_msgs/Path'
      });
      
      this.stateSubscriber = new ROSLIB.Topic({
        ros: this.ros,
        name: '/uav1/prometheus/state',
        messageType: 'prometheus_msgs/UAVState'
      });

      this.controlStateSubscriber = new ROSLIB.Topic({
        ros: this.ros,
        name: '/uav1/prometheus/control_state',
        messageType: 'prometheus_msgs/UAVControlState'
      });

      this.feedbackSubscriber = new ROSLIB.Topic({
        ros: this.ros,
        name: '/uav1/prometheus/text_info',
        messageType: 'prometheus_msgs/TextInfo'
      });

      this.feedbackSubscriber.subscribe((message) => {
        this.addLog(`🔔 ${message.Message}`);
      });

      this.stateSubscriber.subscribe((message) => {
        this.uav_id = message.uav_id || 1;
        this.uavConnected = message.connected || false;
        this.armed = message.armed || false;
        
        this.modeText = message.mode || '未知';
        this.flightMode = this.modeText;
        
        this.locationSource = message.location_source || 0;
        this.odomValid = message.odom_valid || false;
        this.gpsStatus = message.gps_status || 0;
        this.gpsNum = message.gps_num || 0;
        
        if (message.position && Array.isArray(message.position) && message.position.length >= 3) {
          this.position = {
            x: message.position[0] || 0,
            y: message.position[1] || 0,
            z: message.position[2] || 0
          };
        }
        
        this.range = message.range || 0;
        this.rel_alt = message.rel_alt || 0;
        
        this.latitude = message.latitude || 0;
        this.longitude = message.longitude || 0;
        this.altitude = message.altitude || 0;
        
        if (message.attitude && Array.isArray(message.attitude) && message.attitude.length >= 3) {
          this.attitude = {
            roll: message.attitude[0] || 0,
            pitch: message.attitude[1] || 0,
            yaw: message.attitude[2] || 0
          };
        }
        
        this.processBatteryInfo(message);
      });

      this.controlStateSubscriber.subscribe((message) => {
        this.controlState = message.control_state || 0;
      });

      this.addLog('ROS话题订阅完成');
    },
    
    processBatteryInfo(message) {
      if (message.battery_percetage !== undefined) {
        if (message.battery_percetage <= 1.0) {
          this.batteryPercentage = Math.round(message.battery_percetage * 100);
        } else {
          this.batteryPercentage = Math.round(message.battery_percetage);
        }
      } else {
        this.batteryPercentage = 0;
      }
      
      if (message.battery_state !== undefined) {
        this.batteryVoltage = message.battery_state;
      } else {
        this.batteryVoltage = 0;
      }
      
      this.batteryText = this.getBatteryText(this.batteryPercentage);
    },
    
    getBatteryText(percentage) {
      if (percentage <= 0) return '未知';
      if (percentage > 70) return '良好';
      if (percentage > 30) return '一般';
      if (percentage > 10) return '低电量';
      return '严重低电量';
    },

    sendUAVCommand(commandData) {
      if (!this.isConnected || !this.commandPublisher) {
        this.addLog('❌ 错误: 未连接到ROS或发布者未就绪');
        return;
      }

      const now = new Date();
      const secs = Math.floor(now.getTime() / 1000);
      const nsecs = (now.getTime() % 1000) * 1000000;

      const message = new ROSLIB.Message({
        header: {
          stamp: { secs: secs, nsecs: nsecs },
          frame_id: commandData.frame_id || 'world'
        },
        Agent_CMD: commandData.Agent_CMD,
        Control_Level: commandData.Control_Level || 0,
        Move_mode: commandData.Move_mode || 0,
        position_ref: [
          commandData.position_ref?.x || 0,
          commandData.position_ref?.y || 0,
          commandData.position_ref?.z || 0
        ],
        velocity_ref: [0, 0, 0],
        acceleration_ref: [0, 0, 0],
        yaw_ref: commandData.yaw_ref || 0,
        Yaw_Rate_Mode: false,
        yaw_rate_ref: 0,
        att_ref: [0, 0, 0, 1],
        latitude: 0,
        longitude: 0,
        altitude: 0,
        Command_ID: this.commandId
      });

      this.commandPublisher.publish(message);
      
      this.addLog(`📤 发送命令ID: ${this.commandId} - ${this.getCommandText(commandData.Agent_CMD)}`);
      this.commandId++;
    },

    sendSetup(setupData) {
      if (!this.isConnected || !this.setupPublisher) {
        this.addLog('❌ 错误: 未连接到ROS或发布者未就绪');
        return;
      }

      const now = new Date();
      const secs = Math.floor(now.getTime() / 1000);
      const nsecs = (now.getTime() % 1000) * 1000000;

      const message = new ROSLIB.Message({
        header: {
          stamp: { secs: secs, nsecs: nsecs },
          frame_id: 'world'
        },
        cmd: setupData.cmd || 0,
        arming: setupData.arming || false,
        px4_mode: setupData.px4_mode || '',
        control_state: setupData.control_state || ''
      });

      this.setupPublisher.publish(message);
      this.addLog(`⚙️ 发送系统设置: cmd=${setupData.cmd}`);
    },

    sendParamSettings(params) {
      if (!this.isConnected || !this.paramSettingsPublisher) {
        this.addLog('❌ 错误: 未连接到ROS或发布者未就绪');
        return;
      }

      const message = new ROSLIB.Message({
        param_name: params.names || [],
        param_value: params.values || []
      });

      this.paramSettingsPublisher.publish(message);
      this.addLog(`📋 发送参数设置: ${params.names?.length || 0}个参数`);
    },

    sendOffsetPose(offsetData) {
      if (!this.isConnected || !this.offsetPosePublisher) {
        this.addLog('❌ 错误: 未连接到ROS或发布者未就绪');
        return;
      }

      const message = new ROSLIB.Message({
        latitude: offsetData.latitude || 0,
        longitude: offsetData.longitude || 0,
        altitude: offsetData.altitude || 0,
        x: offsetData.x || 0,
        y: offsetData.y || 0,
        z: offsetData.z || 0
      });

      this.offsetPosePublisher.publish(message);
      this.addLog(`📍 发送位置偏移: x=${offsetData.x}, y=${offsetData.y}, z=${offsetData.z}`);
    },

    sendStopControl(stop) {
      if (!this.isConnected || !this.stopControlPublisher) {
        this.addLog('❌ 错误: 未连接到ROS或发布者未就绪');
        return;
      }

      const message = new ROSLIB.Message({
        data: stop
      });

      this.stopControlPublisher.publish(message);
      this.addLog(`⏸️ ${stop ? '停止' : '恢复'}控制状态`);
    },

    publishTrajectory(trajectoryData) {
      if (!this.isConnected || !this.trajectoryPublisher) {
        this.addLog('❌ 错误: 未连接到ROS或发布者未就绪');
        return;
      }

      const message = new ROSLIB.Message(trajectoryData);
      this.trajectoryPublisher.publish(message);
      this.addLog(`📤 发布轨迹到 /uav1/prometheus/trajectory，包含 ${trajectoryData.poses.length} 个路径点`);
    },

    // 修复：删除未使用的 trajectoryOptions 参数
    executeTrajectory() {
      if (!this.isConnected || !this.commandPublisher) {
        this.addLog('❌ 错误: 未连接到ROS或发布者未就绪');
        return;
      }

      const now = new Date();
      const secs = Math.floor(now.getTime() / 1000);
      const nsecs = (now.getTime() % 1000) * 1000000;

      const message = new ROSLIB.Message({
        header: {
          stamp: { secs: secs, nsecs: nsecs },
          frame_id: 'world'
        },
        Agent_CMD: 4, // Move命令
        Control_Level: 0,
        Move_mode: 6, // TRAJECTORY模式
        position_ref: [0, 0, 0],
        velocity_ref: [0, 0, 0],
        acceleration_ref: [0, 0, 0],
        yaw_ref: 0,
        Yaw_Rate_Mode: false,
        yaw_rate_ref: 0,
        att_ref: [0, 0, 0, 1],
        latitude: 0,
        longitude: 0,
        altitude: 0,
        Command_ID: this.commandId
      });

      this.commandPublisher.publish(message);
      this.addLog(`🚀 发送轨迹执行命令 (Move_mode=6)`);
      this.commandId++;
    },

    stopTrajectory() {
      this.sendHover();
      this.addLog('⏹️ 停止轨迹执行');
    },

    sendArm() {
      this.sendUAVCommand({
        Agent_CMD: 1, // Init_Pos_Hover
        Control_Level: 0,
        Move_mode: 0,
        position_ref: { x: 0, y: 0, z: 0 },
        frame_id: 'ENU',
        yaw_ref: this.yawRef
      });
    },

    sendTakeoff() {
      this.sendUAVCommand({
        Agent_CMD: 1, // Init_Pos_Hover
        Control_Level: 0,
        Move_mode: 0,
        position_ref: { x: this.position.x, y: this.position.y, z: 1.5 },
        frame_id: 'ENU',
        yaw_ref: this.yawRef
      });
    },

    sendLand() {
      this.sendUAVCommand({
        Agent_CMD: 3, // Land
        Control_Level: 0,
        frame_id: 'ENU'
      });
    },

    sendDisarm() {
      this.sendUAVCommand({
        Agent_CMD: 4, // Move
        Control_Level: 0,
        frame_id: 'ENU'
      });
    },

    sendHover() {
      this.sendUAVCommand({
        Agent_CMD: 2, // Current_Pos_Hover
        Control_Level: 0,
        Move_mode: 0,
        position_ref: this.position,
        frame_id: 'ENU',
        yaw_ref: this.attitude.yaw
      });
    },

    moveForward() {
      this.sendDirectionMove('forward', this.stepSize);
    },

    moveBackward() {
      this.sendDirectionMove('backward', this.stepSize);
    },

    moveLeft() {
      this.sendDirectionMove('left', this.stepSize);
    },

    moveRight() {
      this.sendDirectionMove('right', this.stepSize);
    },

    moveUp() {
      this.sendDirectionMove('up', this.stepSize);
    },

    moveDown() {
      this.sendDirectionMove('down', this.stepSize);
    },

    sendDirectionMove(direction, step) {
      let positionRef = { ...this.position };
      let moveMode = 0;
      
      if (this.controlMode === 'ENU') {
        switch (direction) {
          case 'forward':
            positionRef.y += step;
            break;
          case 'backward':
            positionRef.y -= step;
            break;
          case 'left':
            positionRef.x -= step;
            break;
          case 'right':
            positionRef.x += step;
            break;
          case 'up':
            positionRef.z += step;
            break;
          case 'down':
            positionRef.z -= step;
            break;
        }
        moveMode = 0; // XYZ_POS
      } else {
        positionRef = { x: 0, y: 0, z: 0 };
        switch (direction) {
          case 'forward':
            positionRef.x = step;
            break;
          case 'backward':
            positionRef.x = -step;
            break;
          case 'left':
            positionRef.y = step;
            break;
          case 'right':
            positionRef.y = -step;
            break;
          case 'up':
            positionRef.z = step;
            break;
          case 'down':
            positionRef.z = -step;
            break;
        }
        moveMode = 3; // XYZ_POS_BODY
      }

      this.sendUAVCommand({
        Agent_CMD: 4, // Move
        Control_Level: 0,
        Move_mode: moveMode,
        position_ref: positionRef,
        frame_id: this.controlMode,
        yaw_ref: this.yawRef
      });
    },

    getCommandText(cmd) {
      const commands = {
        1: '初始位置悬停',
        2: '当前位置悬停',
        3: '降落',
        4: '移动',
        5: '用户模式'
      };
      return commands[cmd] || '未知命令';
    },

    getBatteryClass(level) {
      if (level <= 0) return 'unknown';
      if (level > 70) return 'high';
      if (level > 30) return 'medium';
      return 'low';
    },

    sendCustomDataSegment() {
      if (!this.isConnected || !this.customDataPublisher) {
        this.addLog('❌ 错误: 未连接到ROS或发布者未就绪');
        return;
      }

      if (this.customData.length === 0) {
        this.addLog('❌ 无自定义数据可发送');
        return;
      }

      this.addLog(`📤 发送自定义数据段: ${JSON.stringify(this.customData)}`);
    },

    addCustomData(data) {
      this.customData.push(data);
    },

    removeCustomData(index) {
      this.customData.splice(index, 1);
    },

    updateTrajectory(newTrajectory) {
      this.trajectory = newTrajectory;
    },

    sendGridMapParams(params) {
      this.addLog(`🗺️ 发送栅格地图参数: ${JSON.stringify(params)}`);
    },

    sendPlanningParams(params) {
      this.addLog(`⚙️ 发送规划参数: ${JSON.stringify(params)}`);
    },

    startPlanning() {
      this.addLog('🚀 开始自主规划');
    },

    stopPlanning() {
      this.addLog('⏹️ 停止自主规划');
    },

    replan() {
      this.addLog('🔄 重新规划');
    },

    clearObstacles() {
      this.addLog('🗑️ 清空障碍物');
    },

    setPlanningMode(mode) {
      this.addLog(`🎯 设置规划模式: ${mode}`);
    },

    applyVisualization(params) {
      this.addLog(`👁️ 应用可视化设置: ${JSON.stringify(params)}`);
    },

    sendVisionControl(params) {
      this.addLog(`🎯 发送视觉控制: ${JSON.stringify(params)}`);
    },

    sendVisionTarget(params) {
      this.addLog(`🎯 发送视觉目标: ${JSON.stringify(params)}`);
    },

    sendGimbalControl(params) {
      this.addLog(`📷 发送云台控制: ${JSON.stringify(params)}`);
    },

    sendAttitudeCorrection(enabled) {
      this.addLog(`🧭 ${enabled ? '启用' : '禁用'}姿态修正`);
    },

    startTracking(params) {
      this.addLog(`🎯 开始目标跟踪: ${JSON.stringify(params)}`);
    },

    stopTracking() {
      this.addLog('⏹️ 停止目标跟踪');
    },

    resetTracking() {
      this.addLog('🔄 重置跟踪器');
    },

    applyVisionParams(params) {
      this.addLog(`👁️ 应用视觉参数: ${JSON.stringify(params)}`);
    },

    addLog(message) {
      const timestamp = new Date().toLocaleTimeString();
      this.logs.unshift(`[${timestamp}] ${message}`);
      if (this.logs.length > 100) {
        this.logs.pop();
      }
    },

    clearLogs() {
      this.logs = [];
      this.addLog('日志已清空');
    }
  },
  beforeDestroy() {
    if (this.stateSubscriber) this.stateSubscriber.unsubscribe();
    if (this.controlStateSubscriber) this.controlStateSubscriber.unsubscribe();
    if (this.feedbackSubscriber) this.feedbackSubscriber.unsubscribe();
    if (this.ros) this.ros.close();
  }
};
</script>

<style scoped>
.main-layout {
  display: flex;
  height: 100vh;
  overflow: hidden;
}

.sidebar-nav {
  width: 240px;
  background-color: #1a2b3c;
  color: white;
  height: 100%;
  position: fixed;
  z-index: 10;
}

.sidebar-header {
  padding: 20px;
  border-bottom: 1px solid #263445;
}

.sidebar-header h1 {
  font-size: 18px;
  margin: 0;
  text-align: center;
  color: white;
}

.admin-menu {
  border-right: none;
  margin-top: 20px;
}

.main-content {
  flex: 1;
  margin-left: 240px;
  padding: 20px;
  background-color: #f8f9fa;
  overflow-y: auto;
  height: 100vh;
}

.management-area {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.05);
  min-height: 600px;
  padding: 20px;
}

.control-area {
  /* 飞行控制区域样式 */
}

.status-bar {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  padding: 15px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.05);
  margin-bottom: 20px;
}

.status-item {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 14px;
}

.status-item label {
  font-weight: 600;
  color: #7f8c8d;
}

.status-item span {
  color: #2c3e50;
}

.connected {
  color: #27ae60;
  font-weight: bold;
}

.control-state, .mode-value {
  font-weight: bold;
  color: #e74c3c;
}

.armed {
  color: #27ae60;
  font-weight: bold;
}

.battery {
  font-weight: bold;
  padding: 2px 8px;
  border-radius: 12px;
  color: white;
}

.battery.high {
  background: #2ecc71;
}

.battery.medium {
  background: #f39c12;
}

.battery.low {
  background: #e74c3c;
}

.battery.unknown {
  background: #95a5a6;
}

.function-buttons {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-bottom: 20px;
}

.function-buttons .btn {
  padding: 10px 16px;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 600;
  transition: all 0.3s;
  background: #2c3e50;
  color: white;
  display: flex;
  align-items: center;
  gap: 8px;
}

.function-buttons .btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0,0,0,0.2);
}

.btn-active {
  background: #409EFF !important;
  color: white !important;
  box-shadow: 0 4px 8px rgba(64, 158, 255, 0.3);
}

.content-area {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.05);
  padding: 20px;
  margin-bottom: 20px;
  min-height: 400px;
}

.control-section {
  margin-bottom: 25px;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.05);
}

.control-section h3 {
  margin: 0 0 15px 0;
  color: #2c3e50;
  font-size: 18px;
  display: flex;
  align-items: center;
  gap: 8px;
}

.connection-controls {
  display: flex;
  gap: 10px;
  align-items: center;
  flex-wrap: wrap;
}

.url-input {
  padding: 10px 12px;
  border: 2px solid #e0e0e0;
  border-radius: 4px;
  flex: 1;
  min-width: 200px;
  font-size: 14px;
}

.btn-connect {
  background: #2c3e50;
  color: white;
}

.btn-disconnect {
  background: #95a5a6;
  color: white;
}

.log-section {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.05);
}

.log-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.log-content {
  height: 200px;
  overflow-y: auto;
  border: 1px solid #e0e0e0;
  border-radius: 4px;
  padding: 15px;
  background: #f8f9fa;
  font-family: monospace;
  font-size: 12px;
}

.log-entry {
  padding: 5px 0;
  border-bottom: 1px solid #e9ecef;
  color: #2c3e50;
}

.btn-clear {
  background: #bdc3c7;
  color: #2c3e50;
}

@media (max-width: 1200px) {
  .status-bar {
    gap: 10px;
  }
  
  .function-buttons {
    gap: 8px;
  }
  
  .function-buttons .btn {
    padding: 8px 12px;
    font-size: 13px;
  }
}

@media (max-width: 768px) {
  .sidebar-nav {
    width: 60px;
  }

  .sidebar-header h1, .el-menu-item span {
    display: none;
  }

  .main-content {
    margin-left: 60px;
    padding: 15px;
  }

  .status-item {
    width: 100%;
  }

  .function-buttons {
    flex-direction: column;
  }

  .function-buttons .btn {
    width: 100%;
    justify-content: center;
  }

  .connection-controls {
    flex-direction: column;
    align-items: stretch;
  }
  
  .content-area {
    padding: 15px;
  }
  
  .management-area {
    padding: 15px;
  }
}
</style>